package com.sdgakj.utils.wechat.common.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 缓存
 */
public class MemeryUtil {
    private static final Map<String, Object> cache = new ConcurrentHashMap();
    private static final String EXPIRES = "_expires";
    private static final String CREATE = "_create";

    public static void put(String key, Object value, Long expires) {
        cache.put(key, value);
        cache.put(getCreateKey(key), Long.valueOf(System.currentTimeMillis()));
        cache.put(getExpiresKey(key), Long.valueOf(expires.longValue() * 1000L));
    }

    public static Object get(String key) {
        long curr = System.currentTimeMillis();
        long create = cache.get(getCreateKey(key)) == null ? 0L : Long.parseLong(String.valueOf(cache.get(getCreateKey(key))));
        long expires = cache.get(getExpiresKey(key)) == null ? 0L : Long.parseLong(String.valueOf(cache.get(getExpiresKey(key))));

        if ((create == 0L) || (expires == 0L)) {
            return null;
        }

        if (curr - create > expires) {
            cache.remove(key);
            cache.remove(getCreateKey(key));
            cache.remove(getExpiresKey(key));
            return null;
        }

        return cache.get(key);
    }

    public static void remove(String key) {
        cache.remove(key);
        cache.remove(getCreateKey(key));
        cache.remove(getExpiresKey(key));
    }

    private static String getCreateKey(String key) {
        return key + "_create";
    }

    private static String getExpiresKey(String key) {
        return key + "_expires";
    }

    public static void main(String[] args) throws InterruptedException {
        Object obj1 = get("aaa");
        System.out.println(obj1);

        put("aaa", "asdf-123", Long.valueOf(10L));
        String s = (String) get("aaa");
        System.out.println(s);
        Thread.sleep(15000L);

        s = (String) get("aaa");
        System.out.println(s);
    }
}